package com.bankcomm.luafuction;

import java.util.HashMap;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaObject;
import org.keplerproject.luajava.LuaState;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;

import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.HomeKeyEventBroadCastReceiver;
import com.bankcomm.common.LPMid;
import com.bankcomm.iccard.ICCard_Balance_Query_Activity;
import com.bankcomm.iccard.ICCard_Cash_Load_Activity;
import com.bankcomm.iccard.ICCard_Deal_Logquery_Activity;
import com.bankcomm.ui.BOCWebViewActivity;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.EMPView;
import com.bankcomm.ui.specialwidget.LPAirList;
import com.bankcomm.ui.specialwidget.LPCityChooser;
import com.bankcomm.ui.specialwidget.LPCityChooser.MyLPCityChooser;
import com.bankcomm.util.DownloadThread;
import com.rytong.tools.ui.AtomParser;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.ComponentCopy;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.ui.CutoverView;
import com.rytong.tools.ui.LPAlertDialog;
import com.rytong.tools.ui.LPWebView;
import com.rytong.tools.ui.LayerView;
import com.rytong.tools.ui.WaitProgressDialog;
import com.rytong.tools.utils.EventHandler;
import com.rytong.tools.utils.Utils;

public class LuaWindow {
    // 弹出框加载进度提示标志
    private boolean isProgressDialog;
    // 进度对话框。
    private WaitProgressDialog waitProgress = null;
    // 新页面报文。
    private String content = null;
    // 刷新页面用到的handler。
	private Handler handler = null;
	// 刷新页面用到的runnable。
	private Runnable xmlRunnable = null;
    
    /**
     * 暂时只对手机自带的返回键和home键做返回逻辑处理， 分别定义代表这两个按键的字符串常量
     */
    public final static String BACKSPACESTR = "backspace";
    public final static String HOMESTR = "home";
    
    public LuaWindow() {
        // TODO Auto-generated constructor stub
        try {
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luawindow");
            String luahead = "window = {};";
            String luafc1 = "function window:alert(...)   if arg.n == 1 then  luawindow:alert1(arg[1]) elseif arg.n == 3 then   luawindow:alert2(arg[1], arg[2], arg[3]) elseif arg.n > 3 then luawindow:alert3(arg[1], arg[2], arg[3], arg[4]) end; end;";
            String luafc2 = "function window:close() luawindow:close(); end;";
            String luafc3 = "function window:open(content) luawindow:open(content); end;";
            String luafc4 = "function window:hide(tag,transitionType) luawindow:hide(tag,transitionType); end;";
            String luafc5 = "function window:showContent(content, tag, transitionType) luawindow:showContent(content,tag,transitionType); end;";
            String luafc6 = "function window:showControl(object, tag, transitionType) luawindow:showControl(object, tag,transitionType); end;";

            String luafc = "function window:show(content) luawindow:show(content); end;";
            String luafc7 = "function window:setPhysicalkeyListener(content, fun) luawindow:setPhysicalkeyListener(content, fun); end;";
            String luafc8 = "function window:closeKeyboard() luawindow:closeKeyboard(); end;";
			String luafc9 = "function window:backHome(index) luawindow:backHome(index); end;";
            String luafc10 = "function window:startActivity(name) luawindow:startActivity(name); end;";
            
            String luafc11 = "function window:replaceWithProgress(historyContent) luawindow:replaceWithProgress(historyContent); end;";
            String luafc12 = "function window:setObjectSort(object, id) luawindow:setObjectSort(object, id); end;";
            String luafc13 = "function window:setConverValue(object1, object2) luawindow:setConverValue(object1, object2); end;";
            String luafc14 = "function window:downloadAPK(url) luawindow:downloadAPK(url); end;";
            String luafc15 = "function window:scanAndSub(url,parmName) luawindow:scanAndSub(url,parmName); end;";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(luafc).concat(luafc1).concat(luafc2).concat(luafc3)
                    .concat(luafc4).concat(luafc5).concat(luafc6).concat(luafc7).concat(luafc8).concat(luafc9)
                    .concat(luafc10).concat(luafc11).concat(luafc12).concat(luafc13).concat(luafc14).concat(luafc15));
        } catch (Exception e) {
            Utils.printException(e);
        }
    }
    
    public void startActivity(String name) {
    	Intent intent = new Intent();
    	if (name.equals("ICCard_Balance_Query_Activity")) {
			intent.setClass(ConfigManager.currentView_, ICCard_Balance_Query_Activity.class);
			ConfigManager.currentView_.startActivity(intent);
		} else if (name.equals("ICCard_Cash_Load_Activity")) {
			intent.setClass(ConfigManager.currentView_, ICCard_Cash_Load_Activity.class);
			ConfigManager.currentView_.startActivity(intent);
		} else if (name.equals("ICCard_Deal_Logquery_Activity")) {
			intent.setClass(ConfigManager.currentView_, ICCard_Deal_Logquery_Activity.class);
			ConfigManager.currentView_.startActivity(intent);
		}else if(name.equals("red_shops")){
			LPMid.getInstance().um_.jumpToRedShop((BaseViewCopy)ConfigManager.currentView_,name);
		}else if(name.equals("search_around")){
			LPMid.getInstance().um_.jumpToLocationService((BaseViewCopy)ConfigManager.currentView_, name);	
		}else if(name.equals("one_node_query")){
			LPMid.getInstance().um_.jumpToLocationService((BaseViewCopy)ConfigManager.currentView_, name);
		} 
    }
    
    public void setObjectSort(Object object, String id){
    	if (object instanceof LPAirList) {
			((LPAirList)object).onClickAction(Integer.parseInt(id));
		}
    }
    
    public void setConverValue(Object obj1, Object obj2){
    	if (obj1 instanceof LPCityChooser && obj2 instanceof LPCityChooser) {
			LPCityChooser cc1 = (LPCityChooser) obj1;
			LPCityChooser cc2 = (LPCityChooser) obj2;
			
			String tempName = null;
			String tempValue = null;
			
			tempValue = cc1.getPropertyByName("value");
			tempName = cc1.getCityName(tempValue);
			
			// orgCity 设置提交值
			cc1.setCityValue(cc2.getPropertyByName("value"));
			// 给文本框赋值
			((MyLPCityChooser)cc1.realView_).setText(cc2.getCityName(cc2.getPropertyByName("value")));
			cc1.air_ = "air";
			cc1.setCityStyle((MyLPCityChooser)cc1.realView_, cc2.getCityName(cc2.getPropertyByName("value")));
			
			// dstCity 设置提交值
			cc2.setCityValue(tempValue);
			// 给文本框赋值
			((MyLPCityChooser)cc2.realView_).setText(tempName);
			cc2.air_ = "air";
			cc2.setCityStyle((MyLPCityChooser)cc2.realView_, tempName);
//			Utils.printOutToConsole("---------------  >>>"+tempName + ":" + tempValue
//					+ ":" + cc1.getCityName(tempValue));
		}
    }
    
    public void closeKeyboard() {
        InputMethodManager imm = (InputMethodManager) ConfigManager.currentView_
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != imm && ConfigManager.currentView_.getCurrentFocus() != null) {
            // 关闭键盘
            imm.hideSoftInputFromWindow(ConfigManager.currentView_.getCurrentFocus().getApplicationWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void alert1(Object object) {
        LPMid.getInstance().alert(ConfigManager.currentView_, object.toString(), false);
    }

    public void alert2(final Object text, final Object button, final Object func) {
        if (!ConfigManager.currentView_.isFinishing()) {
            ConfigManager.currentView_.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    String title = text.toString();
                    final LuaObject lo = (LuaObject) func;
                    final String button1 = button.toString();
                    final Builder ad = new AlertDialog.Builder(ConfigManager.currentView_);
                    ad.setTitle("提示").setMessage(title).setCancelable(false);
                    if (func instanceof LuaObject) {

                        ad.setPositiveButton(button1, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                // 如果是lua则将参数代入并执行并执行

                                try {
                                    lo.call(new Object[] { button1 }, 0);
                                } catch (LuaException e) {
                                    // TODO Auto-generated catch block
                                    Utils.printException(e);
                                }
                            }

                        });
                    } else {
                        ad.setPositiveButton(button1, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                // 如果是lua则将参数代入并执行并执行
                            }

                        }).setNegativeButton(func.toString(), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }

                        });
                    }
                    ad.show();
                }
            });

        }
    }

    public void alert3(final Object text, final Object button1, final Object button2, final Object func) {
        if (!ConfigManager.currentView_.isFinishing()) {
            ConfigManager.currentView_.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    String title = text.toString();
                    if (func instanceof LuaObject) {
                        final LuaObject lo = (LuaObject) func;
                        final Builder ad = new AlertDialog.Builder(ConfigManager.currentView_);
                        ad.setTitle("提示").setMessage(title).setCancelable(false)
                                .setPositiveButton(button1.toString(), new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface dialog, int which) {
                                        // TODO Auto-generated method stub
                                        // 如果是lua则将参数代入并执行并执行

                                        try {
                                            lo.call(new Object[] { 0 }, 0);
                                        } catch (LuaException e) {
                                            // TODO Auto-generated catch block
                                            Utils.printException(e);
                                        }
                                    }

                                }).setNegativeButton(button2.toString(), new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        // TODO Auto-generated method stub
                                        try {
                                            lo.call(new Object[] { 1 }, 0);
                                        } catch (LuaException e) {
                                            // TODO Auto-generated catch block
                                            Utils.printException(e);
                                        }
                                    }
                                });
                        ad.show();
                    }
                }
            });
        }
    }

    public void setPhysicalkeyListener(String keyCode, LuaObject function) {
        if (keyCode != null && function != null) {
            if (null == Utils.keyHash_)
            	Utils.keyHash_ = new HashMap<String, LuaObject>();
            if (keyCode.equalsIgnoreCase(BACKSPACESTR)) {
            	Utils.keyHash_.put(BACKSPACESTR, function);
            }
            if (keyCode.equalsIgnoreCase(HOMESTR)) {
               /*注册home按键监听广播*/
				HomeKeyEventBroadCastReceiver receiver = new HomeKeyEventBroadCastReceiver();
				ConfigManager.currentView_.registerReceiver(receiver,
						new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
				Utils.keyHash_.put(HOMESTR, function);
            }
        }

    }

    public void close() {
        // 停止程序开启的服务，保证程序退出后不会常驻内存
        Intent intent = new Intent();
        intent.setAction(getClass().getPackage().getName());
        ConfigManager.currentView_.stopService(intent);
        System.exit(0);
    }

    /**
     * object：当前页面中已有的控件对象 tag: 待显示页面标记
     * 
     * @param object
     * @param tag
     */
    final public void showControl(final Object object, final int tag, final Object transitionType) {
        if (Thread.currentThread().getId() == 1) {
            doShowControl(object, tag, transitionType);
        	
//        	showUpLayer(object, tag, transitionType);
        } else {
            ConfigManager.currentView_.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    doShowControl(object, tag, transitionType);
//                	showUpLayer(object, tag, transitionType);
                }
            });
        }
    }
    
	private void showUpLayer(Object object, int tag, Object transitionType) {

		if (!(object instanceof Component)) {

			return;
		}

		final Component component = (Component) object;
		if (null == component.realView_) {

			return;
		}
		component.disinheritance();
		component.setVisible(View.VISIBLE);

		int type = Integer.valueOf(transitionType.toString());
		LayerView.open(component.realView_, type);
	}
	
	 
	private void setDialogAnimation(Window window, int type) {
		switch (type) {
		case CutoverView.SLIDE_FROM_LEFT:
			window.setWindowAnimations(R.style.dialogWindowLeft);
			break;
		case CutoverView.SLIDE_FROM_RIGHT:
			window.setWindowAnimations(R.style.dialogWindowRight);
			break;
		case CutoverView.SLIDE_FROM_UP:
			window.setWindowAnimations(R.style.dialogWindowUp);
			break;
		case CutoverView.SLIDE_FROM_DOWN:
			window.setWindowAnimations(R.style.dialogWindowDown);
			break;
		}
	}
	
	private void setDialogAnimationOut(Window window, int type){
		switch (type) {
		case CutoverView.SLIDE_FROM_LEFT:
			window.setWindowAnimations(R.style.dialogWindowLeftOut);
			break;
		case CutoverView.SLIDE_FROM_RIGHT:
			window.setWindowAnimations(R.style.dialogWindowRightOut);
			break;
		case CutoverView.SLIDE_FROM_UP:
			window.setWindowAnimations(R.style.dialogWindowUpOut);
			break;
		case CutoverView.SLIDE_FROM_DOWN:
			window.setWindowAnimations(R.style.dialogWindowDownOut);
			break;
		}
	}

    private void doShowControl(final Object object, final int tag, Object transitionType) {
        if (object instanceof Component) {
            // 如果是控件,则首先要检测该控件是否有父控件，如果有，应割断其父子关系
            final Component c = (Component) object;
            if (c.realView_ == null) {
                return;
            }
            c.disinheritance();
            c.setVisible(View.VISIBLE);

            int w = -2;
            int h = -2;
            int left = 0;
            int top = 0;
            android.view.ViewGroup.LayoutParams vlp = c.getLayoutParams();
            if (vlp instanceof android.widget.AbsoluteLayout.LayoutParams) {
                android.widget.AbsoluteLayout.LayoutParams al = (android.widget.AbsoluteLayout.LayoutParams) vlp;
                w = al.width;
                h = al.height;
            } else { //  body
            	w = vlp.width;
            	h = vlp.height;
            }

            CssStyle cs = c.cssStyle();
            if (null != cs) {
                Object temp = cs.getProperty(CssStyle.LEFT);
                if (null != temp && !temp.equals("")) {
                    left = Integer.parseInt(Component.fixedPX((String) temp));
                    left = Utils.getScaledValueX(left);
                }
                temp = cs.getProperty(CssStyle.TOP);
                if (null != temp && !temp.equals("")) {
                    top = Integer.parseInt(Component.fixedPX((String) temp));
                    top = Utils.getScaledValueY(top);
                }
                temp = cs.getProperty(CssStyle.WIDTH);
                if (null != cs && null != temp && !temp.equals("")) {
                    w = Integer.parseInt(Component.fixedPX((String) temp));
                    w = Utils.getScaledValueX(w);
                }
                temp = cs.getProperty(CssStyle.HEIGHT);
                if (null != cs && null != temp && !temp.equals("")) {
                    h = Integer.parseInt(Component.fixedPX((String) temp));
                    h = Utils.getScaledValueY(h);
                }
            }

            final LPAlertDialog dlg = new LPAlertDialog(ConfigManager.currentView_, R.style.alertdialog, c.realView_);
            dlg.setCanceledOnTouchOutside(false);
            dlg.setComponent(c);
            if (isProgressDialog) {
                dlg.setTitle("PROGRESSDIALOG");
                isProgressDialog = false;
            }
            // 给对话框设置标志，标志对话框唯一性
            dlg.setTag(tag);
            Component.DIALOGHASH.put(tag, dlg);
            // 将新建的dialog与控件的activity建立联系,便于管理
            dlg.setOwnerActivity(c.getActivity());

            dlg.setContentView(c.realView_);

            Window mWindow = dlg.getWindow();
            if(transitionType != null){
            	int type = Integer.valueOf(transitionType.toString());
            	setDialogAnimation(mWindow, type);
            }
            WindowManager.LayoutParams lp = mWindow.getAttributes();

            // 确定弹出框的基点，x，y都是在该基点上的偏移
            lp.gravity = android.view.Gravity.TOP | android.view.Gravity.LEFT;
            lp.x = left;
            lp.y = top;
            // 弹出框的宽高本来由里面的容器决定,但是发现当把容器限制好以后显示在弹出框上面宽高不一致,故在此特殊指定一下,具体原因暂不明.
            if (w != 0 || h != 0) {
                lp.width = w;
                lp.height = h;
            }
            mWindow.setLayout(w, h);
            if (Thread.currentThread().getId() == 1) {
            	dlg.show();
            } else {
            	ConfigManager.currentView_.runOnUiThread(new Runnable() {
            	    @Override
            	    public void run() {
            	        dlg.show();
            	    }
            	});
            }
        }
    }

    /**
     * 第一个参数可以接受两种参数类型： content：待显示页面的报文或者本地报文path；本地报文路径（例：local:loading.xml） tag: 待显示页面标记
     * 
     * @param content
     * @param tag
     */
    final public void showContent(Object content, final int tag, Object transitionType) throws SAXException {
    	
    	ComponentCopy.COMPONENTPARTLY = null; 
        String s = (String) content;
        if (s != null && s.startsWith("local")) {
            // 可显示内容为路径,滤掉字符串前面的local:内容
            String path = s.substring(6);
            // 判断路径中是否含有FullSLoading字符串，如果含有，表示该载入内容为进度提示框
            // 该字符串一定要与assets文件夹中的进度提示xml文件名字对应
            if (path.contains("FullSLoading")) {
                isProgressDialog = true;
                s = Utils.getStringFormAsset(ConfigManager.currentView_, path);
            } else {

            	s = Utils.readLocalFileForStr(path);
            }
        }
        if (s == null || s.equals("")) {
            return;
        }
        final AtomParser apc = new AtomParser(ConfigManager.currentView_, AtomParser.PARTLY);
        s = Utils.unescapeHTML(s);
        s = Utils.insteadOfSpecillCharacter(s, true);
        android.util.Xml.parse(s, apc);
        showControl(ComponentCopy.COMPONENTPARTLY, tag, transitionType);
    }

    /**
     * 当前参数可以接受三种参数类型： object：当前页面中已有的控件对象 content：待显示的页面报文内容 path；本地报文路径（例：local:loading.xml） *
     * 
     * @param o
     */
    public void show(Object o) {
        if (o instanceof String) {
            String s = (String) o;
            if (s.indexOf("local") != -1) {
                // 可显示内容为路径
            } else {
                // 可显示内容为报文
                Utils.printOutToConsole(o.toString());
            }
        } else {
            Utils.printOutToConsole(o.toString());
        }
    }

    /**
     * 隐藏之前调用window:showContent()/showContent()方法显示的悬浮页面
     * 
     * @param o
     */
    public void hide(Object index, Object transitionType) {
    	
    	try {
    		Component.LUASTATE.pushObjectValue(new Object());
    		final String luahead = "function close()  ryt:back(); end;";
    		Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
    		Component.LUASTATE.LdoString(luahead);
    	} catch (Exception e) {
    		Utils.printException(e);
    	}
    	 
        try {
            final LPAlertDialog dlg = (LPAlertDialog) Component.DIALOGHASH.get(index);
            if (null != dlg) {
            	if (null != transitionType) {
            		int type = Integer.valueOf(transitionType.toString());
            		setDialogAnimationOut(dlg.getWindow(), type);
            	}  
                if (null != dlg.comp_) {
                    int w = 0;
                    int h = 0;
                    int left = 0;
                    int top = 0;
                    CssStyle cs = dlg.comp_.cssStyle();
                    if (null != cs) {
                        Object temp = cs.getProperty(CssStyle.LEFT);
                        if (null != temp && !temp.equals("")) {
                            left = Integer.parseInt(Component.fixedPX((String) temp));
                            left = Utils.getScaledValueX(left);
                        }
                        temp = cs.getProperty(CssStyle.TOP);
                        if (null != temp && !temp.equals("")) {
                            top = Integer.parseInt(Component.fixedPX((String) temp));
                            top = Utils.getScaledValueY(top);
                        }
                        temp = cs.getProperty(CssStyle.WIDTH);
                        if (null != temp && !temp.equals("")) {
                            w = Integer.parseInt(Component.fixedPX((String) temp));
                            w = Utils.getScaledValueX(w);
                        }
                        temp = cs.getProperty(CssStyle.HEIGHT);
                        if (null != temp && !temp.equals("")) {
                            h = Integer.parseInt(Component.fixedPX((String) temp));
                            h = Utils.getScaledValueY(h);
                        }
                    }

                    final Animation animation = getAnimationWithTransitionType(transitionType, left, top, w, h);
                    if (dlg.comp_.realView_ != null && animation != null) {
                        animation.setAnimationListener(new AnimationListener() {

                            @Override
                            public void onAnimationStart(Animation animation) {
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {
                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                dlg.dismiss();
                            }
                        });
                        dlg.comp_.realView_.startAnimation(animation);
                    } else {
                        dlg.dismiss();
                    }
                } else {
                    dlg.dismiss();
                }
                Component.DIALOGHASH.remove(index);
                Component.VWIDGETARRAY.clear();
            }
        } catch (Exception e) {
            Utils.printException(e);
        }

    }

    /**
     * 根据指定的transitionType返回控件comp的动画
     * 
     * @param comp
     * @param transitionType
     * @return
     */
    private Animation getAnimationWithTransitionType(Object transitionType, int left, int top, int w, int h) {
        Animation animation = null;
        if (transitionType != null) {
            int type = Integer.valueOf(transitionType.toString());
            switch (type) {
            case 0:
                // 翻转效果，从左侧翻转
                animation = new TranslateAnimation(0, w, 0, 0);
                animation.setInterpolator(new LinearInterpolator());
                animation.setDuration(500);
                break;
            case 1:
                // 翻转效果，从右侧翻转
                animation = new TranslateAnimation(w, 0, 0, 0);
                animation.setInterpolator(new LinearInterpolator());
                animation.setDuration(500);
                break;
            case 2:
                // TODO待完善 页面卷曲效果，向上卷曲
                animation = new TranslateAnimation(left, left - w, 0, 0);
                break;
            case 3:
                // TODO待完善 页面卷曲效果，向下卷曲
                animation = new TranslateAnimation(left, left - w, 0, 0);
            default:
                break;
            }
        }
        return animation;
    }

    /**
     * 
     * @param url
     *            新界面的地址
     * @param name
     *            需要更新的控件名称
     * @param channelmode
     *            是否需要弹出新的窗口显示内容,默认为是
     */
    public void open(final String content) {
        if (null != content && !content.equals("")) {
            if (content.indexOf("http") != -1) {
//                // 如果是地址，则用浏览器打开
//                LPWebView wv = new LPWebView();
//
//                wv.initRealView(ConfigManager.currentView_, "");
//                wv.loadUrl(content);
//                ConfigManager.currentView_.setContentView(wv.realView_);
            	
            	//MOD BY ZHAOBIN 修改和ios操作一样打开外部浏览器
            	Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse(content);
                intent.setData(uri);
                ConfigManager.currentView_.startActivity(intent);
            }
//            else if(content.startsWith("inner:")){
//				Intent intent=new Intent( ConfigManager.currentView_,BOCWebViewActivity.class);
//				String url="";
//				url=content.substring(6,content.length());
//				intent.putExtra("url",url);
//				ConfigManager.currentView_.startActivity(intent);
//			}
            else {
                // LPMid.getInstance().waitDialog_.addBgTask(new
                // WaitDialog.Task(0) {
                //
                // Override
                // public void run(WaitDialog dlg) throws Exception {
                // TODO Auto-generated method stub
                // BaseView.initLuaScript();
                AtomParser apc = new AtomParser(ConfigManager.currentView_, AtomParser.ENTIRE);
                try {
                    String reply = Utils.unescapeHTML(content);
                    reply = Utils.insteadOfSpecillCharacter(reply, true);
                    android.util.Xml.parse(reply, apc);
                    ConfigManager.currentView_.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            ConfigManager.currentView_.setContentView(ComponentCopy.COMPONENT.getLPView());
                        }

                    });

                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    Utils.printException(e);
                }
                // }
                // });

            }
        }
    }

    /**
     * 由EWP后台调用的LUA方法，从交易页面跳转到首页
     * index:0-"我的首页"，1-"生活服务"，2-"金融服务"，3-"投资理财"
     * @param index
     */
    public void backHome(int index){
    	LPMid.getInstance().um_.backToHome(ConfigManager.currentView_, index);
    }
    
    /**
     * 返回某个历史页面，带有一个进度提示框。
     * 
     * @param historyContent 需要解析的新页面报文。
     */
    public void replaceWithProgress(final String historyContent){
    	xmlRunnable = new Runnable() {
    		@Override
    		public void run() {
    			if(null == historyContent || "".equalsIgnoreCase(historyContent)){
    				if(null != waitProgress && null != waitProgress.dialog_){
						waitProgress.dialog_.dismiss();
						waitProgress = null;
					}
    				if(null != ConfigManager.currentView_){
    					ConfigManager.currentView_.finish();    					
    				}
    			}
    			content = historyContent;
    			content = Utils.unescapeHTML(content);
    			content = Utils.insteadOfSpecillCharacter(content, true);
    			AtomParser apc = null;
    			if (content.contains("body"))
    				apc = new AtomParser(ConfigManager.currentView_, AtomParser.ENTIRE);
    			else
    				apc = new AtomParser(ConfigManager.currentView_, AtomParser.PARTLY);
    			try {
    				android.util.Xml.parse(content.trim(), apc);
    				ConfigManager.currentView_.runOnUiThread(new Runnable() {
    					@Override
    					public void run() {
    						if(null != waitProgress && null != waitProgress.dialog_){
    							waitProgress.dialog_.dismiss();
    							waitProgress = null;
    						}
    						ConfigManager.currentView_.setContentView(ComponentCopy.COMPONENT.getLPView());
    					}
    				});
    			} catch (SAXException e) {
    				if(null != waitProgress && null != waitProgress.dialog_){
						waitProgress.dialog_.dismiss();
						waitProgress = null;
					}
    				Utils.printException(e);
    			}
    		}
    	};
		if(handler == null){
			handler = new Handler();
		}
		if(Component.ACTIONV != null && Component.ACTIONV.size() >= 1){ // 若栈中有页面，就弹一个dialog出来。
			waitProgress = new WaitProgressDialog(ConfigManager.currentView_);
			waitProgress.show(null);
		}
		handler.postDelayed(xmlRunnable,100);
    }
    
    public void downloadAPK(String downUrl){
    	
    	if (!downUrl.equals("")) {
			Utils.printOutToConsole("下载URL:" + downUrl);
			if(!downUrl.startsWith(Utils.SERVER_URI)){
				if(downUrl.startsWith("/")){
				downUrl=Utils.SERVER_URI.concat(downUrl);
				}
			}
			EMPView act = (EMPView) ConfigManager.currentView_;
			if (act.downloadThread == null) {
				act.downloadThread = new DownloadThread(act);
			}
			act.downloadThread.setApkDownload(downUrl);
			act.downloadThread.downLoad();

		}
	}
    /**
     * url:扫描后提交到的地址
     * parmName:扫描出二维码的参数名
     * ios还没做，跑通后提醒ios加上
     * 
     * **/
    public void scanAndSub(String url ,String parmName){
    	EventHandler uh = EventHandler.getUtHandler();
		Message msg = new Message();
		msg.what = EventHandler.MSG_LUA_SEND_QRCODE;
		Bundle bundleData=new Bundle();
		bundleData.putString("qrUrl", url );
		bundleData.putString("qrParmName", parmName);
		msg.setData(bundleData);
		uh.eventHandler.sendMessage(msg);
    }
}
